package artid.com.arttogoa;

import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
import org.xutils.x;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.http.RequestParams;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.NormalItem;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.GsonUtils;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.volley.BitmapCache;
import artid.com.arttogoa.volley.VolleyBasic;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.umeng.socialize.utils.Log;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 
 * 
 * 项目名称：ArtworkArtA 类名称：UploadPhotoActivity 类描述：上传头像 创建人：耿卫斌 创建时间：2016年5月16日
 * 下午2:37:01
 * 
 */
public class UploadPhotoActivity extends BaseActivity implements
OnClickListener {
	private Button mNext;
	private TextView mJump;
	private Intent in;
	private ImageView personal_img;
	Boolean isSetPic = false;
	private ImageLoader mImageLoader;
	Boolean isRegister = false;//是否是从注册一步步走来的（默认false）
	private String PhotoPath;//剪裁之后的图片路径
	private Bitmap clipBitmap;//剪裁之后的图片
	private String Bitmap64;//剪裁之后的图片流

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload_photo);
		setContent(this, getIntent());
		ArtWorkApp.getInstance().addActivity(this);
		initView();
	}

	private void initView() {
		mContext = this;
		isRegister=getIntent().getBooleanExtra("isRegister", false);
		RequestQueue mQueue = Volley.newRequestQueue(mContext);
		mImageLoader = new ImageLoader(mQueue, new BitmapCache());
		mNext = (Button) findViewById(R.id.upload_next);
		mTittle = (TextView) findViewById(R.id.title_text);
		mTittle.setText("上传头像");
		setBack();
		mBack.setVisibility(View.GONE);
		mFbText = (TextView) findViewById(R.id.title_fb);
		mFbText.setText("跳过");
		mFbText.setVisibility(View.GONE);
		personal_img = (ImageView) findViewById(R.id.UploadPhoto_personal_img);
		personal_img.setOnClickListener(this);
		mFbText.setTextColor(this.getResources().getColor(R.color.jump));
		mFbText.setOnClickListener(this);
		mBack.setOnClickListener(this);
		mNext.setOnClickListener(this);
		// mJump.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.upload_next:
			submitphoto();
			break;
		case R.id.title_fb:
			// 跳过(完善信息)
			in = new Intent(UploadPhotoActivity.this,RealNameAuthenticationActivity.class);
			in.putExtra("isRegister", true);
			startActivity(in);
			break;
		case R.id.UploadPhoto_personal_img:
			//头像选择Dialog
			showPopupWindow();
			break;

		default:
			break;
		}
	}

	// 点击头像，选择照片
	public void showPopupWindow() {
		AlertUtils.initPhotoAlertDialog(mContext,Integer.parseInt(NetUtils.getDisplayMetrics(UploadPhotoActivity.this).get(NetUtils.DM_WIDTH)), new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.tv_phone:
					//检查权限
					if (ContextCompat.checkSelfPermission(UploadPhotoActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
						displayFrameworkBugMessageAndExit();
						return;
					}
					//照相机	
					CameraUtils.openCameraImage(UploadPhotoActivity.this);
					AlertUtils.dismiss();
					break;
				case R.id.tv_choice:
					//从相册获取
					CameraUtils.openLocalImage(UploadPhotoActivity.this);
					AlertUtils.dismiss();
					break;
				default:
					break;
				}
			}
		});
	}


	/**
	 * 上传头像
	 */
	private void submitphoto() {
		VolleyBasic.showLoding(this);
		RequestParams params=new RequestParams(Cache.headinfo);
		params.addHeader("Accept",  "application/json, text/javascript, */*");
		params.addParameter("token", AppUtil.getUser().getToken());
		params.addParameter("headcontent", Bitmap64);
		x.http().post(params, new CommonCallback<String>() {

			@Override
			public void onCancelled(CancelledException cex) {
				// TODO Auto-generated method stub
				System.out.println("主动停止网络请求");
				VolleyBasic.disMissLoding();
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				// TODO Auto-generated method stub
				//请求错误
				if(isOnCallback==false){
					//ex异常信息不是来自回调方法
					System.out.println("ex异常信息不是来自回调方法："+ex.getMessage());
				}else{
					//ex异常信息是来自回调方法
					System.out.println("ex异常信息是来自回调方法："+ex.getMessage());
				}
				VolleyBasic.disMissLoding();
			}

			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				System.out.println("请求完毕,不管成功失败");
			}

			@Override
			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				//成功
				VolleyBasic.disMissLoding();
				String code=GsonUtils.message(result, "ret");
				String message=GsonUtils.message(result, "msg");
				Log.d("log", "上传头像："+result.toString());
				if("1".equals(code)){
					if(!StringUtils.isEmpty(PhotoPath)){
						BitmapUtil.deleteBitmap(PhotoPath);
					}
					//上传成功
					NormalItem bean=GsonUtils.json2bean(result, NormalItem.class);
					String imgUrl = bean.data;
					AppUtil.getUser().setAvatarurl(imgUrl);
					try {
						//保存头像
						String path = null ;
						if(!StringUtils.isEmpty(imgUrl)){
							String[] url = imgUrl.split(".png");//他会把按.分开的部分存储到数组中
							path= Environment.getExternalStorageDirectory() + "/YJB/"+url[0]+"_128_128.png.jpg";
						}
						BitmapUtil.saveBitmapToFile(clipBitmap,path);
						//保存头像地址
						MySharedPreferences.getMySharedPreferences(mContext).setValue("HeadURL"+AppUtil.getUser().getUid(), path);
						in = new Intent(UploadPhotoActivity.this,RealNameAuthenticationActivity.class);
						in.putExtra("isRegister", true);
						startActivity(in);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else if("0".equals(code)){
					showToast(message);
				}else if("-99".equals(code)){
					VolleyBasic.showRemoteLoginDialog(UploadPhotoActivity.this);
				}
			}
		});
	}

	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
		// TODO Auto-generated method stub  
		super.onActivityResult(requestCode, resultCode, data);  
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri=CameraUtils.imageUriFromCamera;
			if(uri != null) {
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath",  BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}else{
				//防止文件不会立马创建
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						if(uri != null) {
							Intent i=new Intent(mContext,Clip_Activity.class);
							i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
							startActivityForResult(i, 200);
						}
					}
				}, 1000);
			}
		} else if (requestCode == CameraUtils.GET_IMAGE_FROM_PHONE) {
			//判断是否从相册中获取图片
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}
		} else if(requestCode==200){
			if(data!=null){
				//获取剪切后的图片路径
				PhotoPath=data.getExtras().getString("PhotoPath");  
				if(!StringUtils.isEmpty(PhotoPath)){
					clipBitmap=BitmapUtil.getSmallBitmap(PhotoPath, 500, 500);
					//设置图片
					personal_img.setImageBitmap(clipBitmap);
					Bitmap64= BitmapUtil.bitmaptoString(clipBitmap);
				}
			}
		}
	}


}
